﻿
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace SharePoint.Orm.Helpers {
	///<summary>
	/// Methods for working with <see cref="IEnumerable"/> or <see cref="IEnumerable{T}"/>
	///</summary>
	public static class IEnumerableHelper {
		/// <summary>
		/// calls an action for each item in a <see cref="IEnumerable"/>.
		/// </summary>
		/// <param name="items">The items to enumerate over.</param>
		/// <param name="action">The action to call for each item.</param>
		public static void Each(this IEnumerable items, Action<object> action) {
			foreach (object item in items) {
				action(item);
			}
		}

		/// <summary>
		/// calls an action for each item in a <see cref="IEnumerable{T}"/>.
		/// </summary>
		/// <typeparam name="T">The type.</typeparam>
		/// <param name="items">The items to enumerate over.</param>
		/// <param name="action">The action to call for each item.</param>
		public static void Each<T>(this IEnumerable<T> items, Action<T> action) {
			foreach (T item in items) {
				action(item);
			}
		}

		/// <summary>
		/// calls an action with the index from the beginning for each item in a <see cref="IEnumerable"/>.
		/// </summary>
		/// <param name="items">The items to enumerate over</param>
		/// <param name="action">The action to call for each item</param>
		public static void Each(this IEnumerable items, Action<object, int> action) {
			int i = 0;
			foreach (object item in items) {
				action(item, i);
				i++;
			}
		}

		/// <summary>
		/// calls an action with the index from the beginning for each item in a <see cref="IEnumerable{T}"/>.
		/// </summary>
		/// <typeparam name="T">The type</typeparam>
		/// <param name="items">The items to enumerate over</param>
		/// <param name="action">The action to call for each item</param>
		public static void Each<T>(this IEnumerable<T> items, Action<T, int> action) {
			int i = 0;
			foreach (T item in items) {
				action(item, i);
				i++;
			}
		}

		///<summary>
		/// Converts a list of items into a delimited string.
		///</summary>
		///<param name="items">The items to iterate over</param>
		///<param name="delimiter">The delimiter to place in between each item</param>
		///<returns>The delimited string</returns>
		public static string ToDelimitedString(this IEnumerable items, string delimiter) {
			StringBuilder results = new StringBuilder();
			Each(items, (item, i) => {
				if (i != 0) {
					results.Append(delimiter);
				}
				results.Append(item);
			});
			return results.ToString();
		}
	}
}
